//
//  YStockChartViewController.m
//  BTC-Kline
//
//  Created by yate1996 on 16/4/27.
//  Copyright © 2016年 yate1996. All rights reserved.
//

#import "Y_StockChartViewController.h"
#import "Masonry.h"
#import "Y_StockChartView.h"
#import "Y_KLineGroupModel.h"
#import "UIColor+Y_StockChart.h"
#import "AppDelegate.h"
#import "UIDevice+TFDevice.h"
#import "LoginViewController.h"
#import "Y_KLineMAView.h"
#import "UIViewController+BackButtonHandler.h"
#import "Y_StockChartGlobalVariable.h"
#import "WebSocket.h"
#import "Y_ChartTableHeadView.h"
#import "MYSegmentView.h"
#import "MainTouchTableTableView.h"
#import "RecordViewController.h"
#import "SymbolInfoViewController.h"
#import "LeftViewController.h"
#import "UIViewController+CWLateralSlide.h"
#import "UIViewController+INMOChildViewControlers.h"
#import "LineKFullScreenViewController.h"
#import "Y_KLineModel.h"
#import "ChatModle.h"
typedef NS_ENUM(NSInteger, KLineTimeType) {
    KLineTimeTypeMinute = 100,
    KLineTimeTypeMinute5,
    KLineTimeTypeMinute15,
    KLineTimeTypeMinute30,
    KLineTimeTypeHour,
    KLineTimeTypeHour4,
    KLineTimeTypeDay,
    KLineTimeTypeWeek,
    KLineTimeTypeMonth,
    KLineTimeTypeOther
};
@interface Y_StockChartViewController ()<Y_StockChartViewDataSource,UIApplicationDelegate,UITableViewDelegate,UITableViewDataSource,SRWebSocketDelegate,Y_StockChartViewDelegate,UIGestureRecognizerDelegate>
/*
  tableView 手势重复
 */
@property (nonatomic, strong) MainTouchTableTableView * stocktableView;
/*
  lineKFullScreenViewController 横屏
 */
@property (strong, nonatomic) LineKFullScreenViewController *lineKFullScreenViewController;
/*
   lineKView 主k线图
 */
@property (nonatomic, strong) Y_StockChartView *lineKView;
/*
 headView tableviewHeadView
 */
@property (nonatomic, strong) Y_ChartTableHeadView *headView;
/*
 groupModel 数据字典
 */
@property (nonatomic, strong) Y_KLineGroupModel *groupModel;
/*
 webSocket webSocket
 */
@property (nonatomic, strong) SRWebSocket *webSocket;
/*
 RecordVCt 成交记录视图
 */
@property (nonatomic, strong) RecordViewController *RecordVCt;
/*
 canScroll tableview是否可以滑动
 */
@property (nonatomic, assign) BOOL canScroll;
/*
 isTopIsCanNotMoveTabView tableview是否可以滑动
 */
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabView;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabViewPre;
@property (assign, nonatomic) BOOL isShowKLineFullScreenViewController;
/*
 iscollection 该交易对是否收藏过
 */
@property (nonatomic, assign) BOOL iscollection;
/*
 NOResh  侧滑不需要刷新
 */
@property (nonatomic, assign) BOOL NOResh;//
/*
 canSegment  没有请求成功介绍l内容不否需要加载segment
 */
@property (nonatomic, assign) BOOL canSegment;
/*
 currentIndex  索引
 */
@property (nonatomic, assign) NSInteger currentIndex;
/**
 *  kLine-MAView
 */
@property (nonatomic, strong) Y_KLineMAView *kLineMAView;
@property (nonatomic, copy) NSMutableDictionary <NSString*, Y_KLineGroupModel*> *modelsDict;
/**
 *  timestr websoket请求的时间差
 */
@property (nonatomic, copy) NSString *timestr;
/**
 *  type
 */
@property (nonatomic, copy) NSString *type;
/**
 *  oldType 旧type 移除掉重新加载
 */
@property (nonatomic, copy) NSString *oldType;
/**
 *  bottomView
 */
@property (nonatomic, strong) UIView * bottomView;
/**
 *  买入
 */
@property (nonatomic, strong) UIButton * PurchaseButton;
/**
 *  卖出
 */
@property (nonatomic, strong) UIButton * SellOutButton;
/**
 *  //收藏
 */
@property (nonatomic, strong) UIButton * collectionbutton;
/**
 *  左边查看所有交易对
 */
@property (nonatomic, strong) UIButton* titlebutton;
/**
 *  dic//币的详情信息
 */
@property (nonatomic, strong) NSDictionary * dic;
/**
 *  //k线图所有数据
 */
@property (nonatomic, strong) NSMutableArray * dataArray;
/**
 *  //盘口数据
 */
@property (nonatomic, strong) NSMutableArray * tradingArray;
@end

@implementation Y_StockChartViewController
- (void)viewWillAppear:(BOOL)animated
{
    if (!_NOResh) {
        [self reconnect];
    }
    [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏1
    [self SetnavigationBarBackgroundImage:[UIColor backgroundColor] Alpha:1];
    [self SetTheLoadProperties:NO];
    [self statusBarStyleIsDark:NO];
    [super viewWillAppear:animated];
}
-(void)dealloc
{
    _webSocket.delegate = nil;
    [_webSocket close];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self statusBarStyleIsDark:[ZBLocalized sharedInstance].StatusBarStyle];
    [self SetTheLoadProperties:YES];
    [self SetnavigationBarBackgroundImage:MAINBLACKCOLOR Alpha:1];
}
- (void)reconnect
{
    [self.modelsDict removeAllObjects];
    _webSocket.delegate = nil;
    [_webSocket close];
    _webSocket = [[SRWebSocket alloc] initWithURL:[NSURL URLWithString:WBSCOKETHOST_IP]];
    _webSocket.delegate = self;
    if (self.webSocket.readyState == SR_OPEN) {
        [self.webSocket sendPing:[EXUnit NSJSONSerializationWithmethod:@"server.ping" parameter:@[] id:1002]];
    }
    [_webSocket open];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.activityIndicatorView.tintColor = [UIColor whiteColor];
    self.activityIndicatorView.type = DGActivityIndicatorAnimationTypeBallSpinFadeLoader;
    [self showLoadingAnimation];
    self.currentIndex = -1;
    self.canSegment = NO;
    self.navigationItem.title = @"";
    self.navigationItem.leftBarButtonItem  = [[UIBarButtonItem alloc] initWithCustomView:self.leftItem];
    self.view.backgroundColor = [UIColor backgroundColor];
    [self.view addSubview:self.stocktableView];
    [self.view addSubview:self.bottomView];
    [_bottomView addSubview:self.PurchaseButton];
    [_bottomView addSubview:self.SellOutButton];
    [_bottomView addSubview:self.collectionbutton];
    NSMutableArray * array = [ EXUnit getCollectionData];
    for (NSString * name in array) {
        if (name == _modle.name) {
            _iscollection = YES;
        }
    }
    _collectionbutton.selected = _iscollection;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(leaveTop:) name:@"leaveTop" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdateBPrice:) name:updateSymbolNotificationse object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(leftSymbolN:) name:leftSymbolNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(scrollViewDidEnd) name:scrollViewDidEndNotificationse object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(scrollViewbegin) name:scrollViewbeginNotificationse object:nil];
    [self getAssetInfoData];
}
// 开始滑动
- (void)scrollViewbegin
{
    _stocktableView.scrollEnabled = NO;
}
// 结束滑动
- (void)scrollViewDidEnd
{
    _stocktableView.scrollEnabled = YES;
}
- (UIView *)leftItem
{
    NSArray *titlearray = [self.modle.name componentsSeparatedByString:@"_"];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 240, 40)];
    view.backgroundColor = [UIColor clearColor];
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
    [button setImage:[UIImage imageNamed:@"K_goback"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    button.centerY = view.centerY;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [view addSubview:button];
    UIImageView * imageView = [UIImageView dd_imageViewWithFrame:CGRectMake(button.right, 0, 1, 16) islayer:NO imageStr:@"K_line"];
    imageView.centerY = view.centerY;
    [view addSubview:imageView];
    
    _titlebutton = [[UIButton alloc] initWithFrame:CGRectMake(imageView.right+12, 0, 240, 30)];
    [_titlebutton setImage:[UIImage imageNamed:@"title-species_b"] forState:UIControlStateNormal];
    [_titlebutton setTitle:[NSString stringWithFormat:@" %@/%@",titlearray[0],titlearray[1]] forState:0];
    [_titlebutton addTarget:self action:@selector(defaultAnimationFromLeft) forControlEvents:UIControlEventTouchUpInside];
    _titlebutton.titleLabel.font = AutoFont(18);
    [_titlebutton setTitleColor:[UIColor whiteColor] forState:0];
    _titlebutton.centerY = view.centerY;
    _titlebutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [view addSubview:_titlebutton];
    
    return view;
}
// 仿QQ从左侧划出
- (void)defaultAnimationFromLeft {
    _NOResh = YES;
    // 自己随心所欲创建的一个控制器
    LeftViewController *vc = [[LeftViewController alloc] init];
    vc.drawerType = DrawerDefaultLeft; // 为了表示各种场景才加上这个判断，如果只有单一场景这行代码完全不需要
    [self cw_showDefaultDrawerViewController:vc];
}
- (void)leftSymbolN:(NSNotification *)message
{
    HomeModle * modle = message.object;
    if (![modle.name isEqualToString:_modle.name])
    {
        [self stopLoadingAnimation];
        _modle = modle;
        NSArray *titlearray = [self.modle.name componentsSeparatedByString:@"_"];
        [self reloadPrice:modle];
        NSMutableArray * array = [ EXUnit getCollectionData];
        for (NSString * name in array) {
            if (name == _modle.name) {
                _iscollection = YES;
            }
        }
        _collectionbutton.selected = _iscollection;
        [self reconnect];
        [self getAssetInfoData];
        [_titlebutton setTitle:[NSString stringWithFormat:@" %@/%@",titlearray[0],titlearray[1]] forState:0];
    }
}
- (void)goBack
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _webSocket.delegate = nil;
    [_webSocket close];
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
    //切换到竖屏
    [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)getAssetInfoData
{
    WeakSelf
    NSArray *namearray = [self.modle.name componentsSeparatedByString:@"_"];
    NSString* hostApi = [NSString stringWithFormat:@"%@/%@",assetIntro,namearray[0]];
    [HomeViewModel getAssetInfoWithDic:@{} url:hostApi callBack:^(BOOL isSuccess, id callBack) {
        weakSelf.canSegment = YES;
        if (isSuccess) {
            weakSelf.dic = callBack;
        }
         [weakSelf.stocktableView reloadData];
    }];
}
- (void)UpdateBPrice:(NSNotification *)message
{
    HomeModle * modle = message.object;
    if (modle.name ==_modle.name) {
        [self reloadPrice:modle];
    }
}
/*
 1546943400,
 0.01850662,
 0.01850786,
 0.01850786,
 0.01850662,
 52.7571,
 0.976389631848,
 EOS_ETH
 */
- (void)reloadPrice:(HomeModle *)modle
{
    _modle = modle;
    NSArray * ary = @[[EXUnit getNowTimeTimestamp],_modle.open,_modle.last,_modle.high,_modle.low,_modle.volume,_modle.name,@"0"];
    
    WeakSelf
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.groupModel != nil &&weakSelf.dataArray.count>0) {
            
            if ([self.type isEqualToString:@"1day"] || [self.type isEqualToString:@"1week"] ||[self.type isEqualToString:@"1month"] ) {
                
                Y_KLineModel *lineModel = [self.groupModel.models lastObject];
                [lineModel initWithArray:ary];
                [self.lineKView.kLineView reDraw];
            }else
            {
                
                Y_KLineModel *lineModel = [self.groupModel.models lastObject];
                [lineModel initWithArray:ary];
                [self.lineKView.kLineView reDraw];
                
            }
            
        }
        [weakSelf.headView reloadData:weakSelf.modle];
    });
    
}
// 收藏
- (void)Collection
{
    [_collectionbutton centerVerticallyImageAndTextWithPadding:6];
    if (_iscollection) {
        
        [EXUnit removoveWithmarket:_modle.name];
        _collectionbutton.selected = NO;
        
    }else
    {
        [EXUnit saveCollectionDataUserDefaultsWith:_modle.name];
        _collectionbutton.selected = YES;
    }
    _iscollection = !_iscollection;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:CollectionNotificationse object:nil];
}

- (NSMutableDictionary<NSString *,Y_KLineGroupModel *> *)modelsDict
{
    if (!_modelsDict) {
        _modelsDict = @{}.mutableCopy;
    }
    return _modelsDict;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of  nmthat can be recreated.
}
#pragma mark - Y_StockChartViewDataSource

-(id)stockDatasWithIndex:(NSInteger)index {
    
    _oldType = self.type;
    switch (index) {
        case 0:
        {    self.type = @"1min";
            _timestr =@"60";
        }
            break;
        case 1:
            self.type = @"15min";
            _timestr =@"900";
            break;
        case 2:self.type = @"4hour";
            _timestr =@"14400";
            break;
        case 3:self.type = @"1day";
            _timestr =@"86400";
            break;
        case 4:self.type = @"1min";
            _timestr =@"60";
            break;
        case 5:self.type = @"5min";
            _timestr =@"300";
            break;
        case 6:self.type = @"30min";
            _timestr =@"1800";
            break;
        case 7:self.type = @"1hour";
            _timestr =@"3600";
            break;
        case 8:self.type = @"1week";
            _timestr =@"604800";
            break;
        case 9:self.type = @"1month";
            _timestr =@"2592000";
            break;
        default:
            break;
    }
    
    self.currentIndex = index;
    if (index == 0 || index == 1 || index == 2 || index == 3) {
        _lineKView.isMoreTimeDataUpdate = NO;
    }
    else{
        _lineKView.isMoreTimeDataUpdate = YES;
    }
    if(![self.modelsDict objectForKey:self.type]){
        if (![NSString isEmptyString:_oldType]) {
            [self.modelsDict removeObjectForKey:_oldType];
        }
        
        [self reloadData];
        
    }
    else{
        NSArray *array = [self.modelsDict objectForKey:self.type].models;
        
        return array;
    }
    
    return nil;
}

- (void)showKLineFullScreenViewController{
    
    [self HorizontalScreen];
    
}
- (void)HorizontalScreen
{
    [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏1
    ///切换到竖屏
    [self allowRotation:YES];
    
}
//横屏竖屏
- (void)allowRotation:(BOOL)allowRotation
{
    
    if (!_lineKFullScreenViewController) {
        
        _lineKFullScreenViewController = [LineKFullScreenViewController loadFromStoryboard];;
    }
    _lineKFullScreenViewController.modle = _modle;
    WeakSelf;
    if (allowRotation) { //横屏
        
        [UIView animateWithDuration:0.35 animations:^{
            
            AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            
            appDelegate.allowRotation = YES;
            [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
        } completion:^(BOOL finished) {
            
            weakSelf.isShowKLineFullScreenViewController = YES;
            [weakSelf containerAddChildViewController:weakSelf.lineKFullScreenViewController parentView:self.view];
            [weakSelf.navigationController setNavigationBarHidden:YES animated:NO]; //设置隐藏1
            
        }];
    }
    
    _lineKFullScreenViewController.onClickBackButton = ^(LineKFullScreenViewController *controller) { //竖屏
        
        [UIView animateWithDuration:0.35 animations:^{
            
            [weakSelf.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏1
            weakSelf.isShowKLineFullScreenViewController = NO;
            [weakSelf containerRemoveChildViewController:weakSelf.lineKFullScreenViewController];
            
            [weakSelf statusBarStyleIsDark:NO];
            [weakSelf.headView reloadData:weakSelf.modle];
            
            AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            appDelegate.allowRotation = NO;
            [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
            
            
        } completion:^(BOOL finished) {
            
            
            
            
        }];
    };
 
}
- (void)reloadData
{
    
    if (_groupModel) {
        [_dataArray removeAllObjects];
        [self showLoadingAnimation];
        NSInteger  endTime = [EXUnit getNowTimeTimestamp].integerValue; //就是当前时间
        float kCount;
        if ([self.type isEqualToString:@"1month"])
        {
            kCount = (UIScreenWidth -Y_StockChartKLinePriceViewWidth)/[Y_StockChartGlobalVariable kLineWidth];
        }else
        {
            kCount = (UIScreenWidth -Y_StockChartKLinePriceViewWidth)/0.5;
        }
        NSInteger  beginTime = endTime - (kCount*self.timestr.integerValue);  //开始时间
        
        NSArray * dataArray = @[_modle.name,@(beginTime),@(endTime),@(self.timestr.integerValue)];
        
        NSData *data = [EXUnit NSJSONSerializationWithmethod:@"kline.query" parameter:dataArray id:1020];
        [_webSocket send:data];    // 发送数据
        
    }
    
    
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (NSMutableArray *)tradingArray
{
    if (!_tradingArray) {
        _tradingArray = [[NSMutableArray alloc] init];
    }
    return _tradingArray;
}
//Y_StockChartSegmentView  Y_KLineMainView; kLineMAView  _VolumeMA7Label Y_KLineView backgroundColor
- (Y_StockChartView *)lineKView
{
    if(!_lineKView) {
        _lineKView = [[Y_StockChartView alloc] initWithFrame:CGRectMake(0, _headView.bottom +5, UIScreenWidth, 395)];
        _lineKView.backgroundColor = [UIColor backgroundColor];
        _lineKView.isFullScreen = NO;
        _isShowKLineFullScreenViewController = NO;
        _lineKView.itemModels = @[
                                  [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_sharing") type:Y_StockChartcenterViewTypeKline],
                                  [Y_StockChartViewItemModel itemModelWithTitle:[NSString stringWithFormat:@"15%@",Localized(@"hone_min")] type:Y_StockChartcenterViewTypeKline],
                                  [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_three_H_line") type:Y_StockChartcenterViewTypeKline],
                                  [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_1_day_line") type:Y_StockChartcenterViewTypeKline],
                                  [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"home_more") type:Y_StockChartcenterViewTypeOther],
                                  [Y_StockChartViewItemModel itemModelWithTitle:Localized(@"hone_index") type:Y_StockChartcenterViewTypeOther],
                                  [Y_StockChartViewItemModel itemModelWithTitle:@"" type:Y_StockChartcenterViewTypeOther],
                                  ];
        _lineKView.dataSource = self;
        _lineKView.delegate = self;
        
        
        
    }
    return _lineKView;
}
- (Y_ChartTableHeadView *)headView
{
    if (!_headView) {
        _headView = [[Y_ChartTableHeadView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
        [_headView reloadData:_modle];
        
    }
    return _headView;
}
#pragma  mark -----懒加载
- (MainTouchTableTableView *)stocktableView
{
    if (!_stocktableView) {
        _stocktableView = [[MainTouchTableTableView alloc]initWithFrame:CGRectMake(0,
                                                                                   0,
                                                                                   UIScreenWidth,
                                                                                   UIScreenHeight - kStatusBarAndNavigationBarHeight - 45 -IPhoneBottom)style:UITableViewStylePlain];
        _stocktableView.tableFooterView = [UIView new];
        _stocktableView.separatorColor = CLEARCOLOR;
        _stocktableView.delegate = self;
        _stocktableView.dataSource=self;
        _stocktableView.backgroundColor =  [UIColor backgroundColor];
        _stocktableView.rowHeight = UIScreenHeight;
        _stocktableView.rowHeight = UITableViewAutomaticDimension;
        _stocktableView.showsVerticalScrollIndicator = NO;
        _stocktableView.bounces = NO;
        _stocktableView.alwaysBounceHorizontal = NO;
        _stocktableView.panGestureRecognizer.delaysTouchesBegan=YES;
        _stocktableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, -500, UIScreenWidth, 500)];
        _stocktableView.tableHeaderView.backgroundColor = ColorStr(@"#14141F");
        [_stocktableView.tableHeaderView addSubview:self.headView];
        [_stocktableView.tableHeaderView addSubview:self.lineKView];
        
        
    }
    return _stocktableView;
}
- (UIView *)bottomView
{
    if (!_bottomView ) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, UIScreenHeight -45 - kStatusBarAndNavigationBarHeight - IPhoneBottom, UIScreenWidth, 45)];
        _bottomView.backgroundColor = [UIColor assistBackgroundColor];
    }
    return _bottomView;
}
/*买入*/
- (UIButton *)PurchaseButton
{
    WeakSelf
    if (!_PurchaseButton) {
        _PurchaseButton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(0,
                                                                              0,
                                                                              RealValue_W(280),
                                                                              _bottomView.height)
                                                             title:Localized(@"hone_Purchase") backgroundColor:ZHANGCOLOR titleColor:WHITECOLOR tapAction:^(UIButton *button) {
                                                                 if (weakSelf.isHomePush) {
                                                                     [self.navigationController popViewControllerAnimated:YES];
                                                                     [AppDelegate shareAppdelegate].index = 0;
                                                                 }else
                                                                 {
                                                                     if ([NSString isEmptyString:[EXUserManager userInfo].token])
                                                                     {
                                                                         [self exitLogon];
                                                                         return;
                                                                     }
                                                                     [AppDelegate shareAppdelegate].index = 0;
                                                                     [AppDelegate shareAppdelegate].modle = weakSelf.modle;
                                                                     self.navigationController.tabBarController.hidesBottomBarWhenPushed=NO;
                                                                     self.navigationController.tabBarController.selectedIndex = 2;  //
                                                                     [self.navigationController popViewControllerAnimated:YES];
                                                                 }
                                                                 
                                                             }];
        _PurchaseButton.titleLabel.font = AutoFont(15);
    }
    return _PurchaseButton;
}
- (void)exitLogon
{
    LoginViewController * loginView = [[LoginViewController alloc] init];
    [[EXUnit currentViewController] presentViewController:loginView animated:YES completion:nil];
}
/*卖出*/
- (UIButton *)SellOutButton
{
    if (!_SellOutButton) {
        WeakSelf
        _SellOutButton = [UIButton dd_buttonCustomButtonWithFrame:CGRectMake(_PurchaseButton.right,
                                                                             _PurchaseButton.mj_y,
                                                                             _PurchaseButton.width,
                                                                             _bottomView.height)
                                                            title:Localized(@"hone_sell") backgroundColor:DIEECOLOR titleColor:WHITECOLOR tapAction:^(UIButton *button) {
                                                                
                                                                
                                                                if (weakSelf.isHomePush) {
                                                                    [self.navigationController popViewControllerAnimated:YES];
                                                                    [AppDelegate shareAppdelegate].index = 1;
                                                                }else
                                                                {
                                                                    if ([NSString isEmptyString:[EXUserManager userInfo].token])
                                                                    {
                                                                        [self exitLogon];
                                                                        return;
                                                                    }
                                                                    [AppDelegate shareAppdelegate].index = 1;
                                                                    [AppDelegate shareAppdelegate].modle = weakSelf.modle;
                                                                    self.navigationController.tabBarController.hidesBottomBarWhenPushed=NO;
                                                                    self.navigationController.tabBarController.selectedIndex = 2;  //
                                                                    [self.navigationController popViewControllerAnimated:YES];
                                                                }
                                                                
                                                            }];
        _SellOutButton.titleLabel.font = AutoFont(15);
    }
    return _SellOutButton;
    
}
- (UIButton *)collectionbutton
{
    if (!_collectionbutton) {
        _collectionbutton = [[UIButton alloc] initWithFrame:CGRectMake(_SellOutButton.right, 0, UIScreenWidth - RealValue_W(560),  _bottomView.height)];
        [_collectionbutton setImage:[UIImage imageNamed:@"title-mark02"] forState:UIControlStateNormal];
        [_collectionbutton setImage:[UIImage imageNamed:@"title-mark01"] forState:UIControlStateSelected];
        [_collectionbutton setTitleColor:ColorStr(@"#9292AD") forState:UIControlStateNormal];
        [_collectionbutton setTitle:Localized(@"k_Collection") forState:UIControlStateNormal];
        [_collectionbutton setTitle:Localized(@"k_Collection_cancel") forState:UIControlStateSelected];
        _collectionbutton.titleLabel.font = AutoFont(10);
        [_collectionbutton centerVerticallyImageAndTextWithPadding:6];
        [_collectionbutton addTarget:self action:@selector(Collection) forControlEvents:UIControlEventTouchUpInside];
    }
    return _collectionbutton;
    
}
#pragma  mark -----tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UIScreenHeight;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor backgroundColor];
     if (self.canSegment) {
         
          [cell.contentView addSubview:self.segmentView];
     }
    return cell;
}
- (UIView *)segmentView
{
    _RecordVCt = [[RecordViewController alloc] init];
    _RecordVCt.modle = _modle;
    SymbolInfoViewController *SymbolInfoVC = [[SymbolInfoViewController alloc] init];
    SymbolInfoVC.modle = _modle;
    SymbolInfoVC.data = _dic;
    NSArray *controllerArray;
    NSArray *titleArray;
    if (_dic.count >0) {
        controllerArray = @[_RecordVCt,SymbolInfoVC];
        titleArray = @[Localized(@"quotation_RECORD"),Localized(@"quotation_symbol_info")];
    }else
    {
        controllerArray = @[_RecordVCt];
        titleArray = @[Localized(@"quotation_RECORD")];
    }
    MYSegmentView * segmentView = [[MYSegmentView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight  - IPhoneBottom -kStatusBarAndNavigationBarHeight) controllers:controllerArray titleArray:titleArray ParentController:self lineWidth:RealValue_H(250) lineHeight:3];
    segmentView.backgroundColor = [UIColor backgroundColor];
    return segmentView;
}
- (void)leaveTop:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat yOffset  = scrollView.contentOffset.y;
    CGFloat tabOffsetY = [_stocktableView rectForSection:0].origin.y;
    _isTopIsCanNotMoveTabViewPre = _isTopIsCanNotMoveTabView;
    scrollView.scrollEnabled = YES;
    
    if (yOffset >= tabOffsetY) {
        
        //不能滑动
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        _isTopIsCanNotMoveTabView = YES;
        
    }else{
        
        //可以滑动
        _isTopIsCanNotMoveTabView = NO;
        
    }
    if (_isTopIsCanNotMoveTabView != _isTopIsCanNotMoveTabViewPre) {
        
        if (!_isTopIsCanNotMoveTabViewPre && _isTopIsCanNotMoveTabView) {
            //NSLog(@"子视图控制器滑动到顶端");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"goTop" object:nil userInfo:@{@"canScroll":@"1"}];
            _canScroll = NO;
        }
        if(_isTopIsCanNotMoveTabViewPre && !_isTopIsCanNotMoveTabView){
            //NSLog(@"父视图控制器滑动到顶端");
            if (!_canScroll) {
                
                scrollView.contentOffset = CGPointMake(0, tabOffsetY);
            }
        }
    }
    
    //    self.tableOffsetY = scrollView.contentOffset.y;
}
#pragma mark - SRWebSocketDelegate
///--------------------------------------
// 成功连接
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
    NSInteger  endTime = [EXUnit getNowTimeTimestamp].integerValue; //就是当前时间
    NSLog(@"-->%f ---%d",[Y_StockChartGlobalVariable kLineWidth] ,Y_StockChartKLineMinWidth);
    float kCount = (UIScreenWidth -Y_StockChartKLinePriceViewWidth) / 0.5; //一行显示多少跟线
    NSInteger  beginTime = endTime - (kCount*_timestr.integerValue);  //开始时间
    NSArray * dataArray = @[_modle.name,@(beginTime),@(endTime),@(_timestr.integerValue)];
    NSData *data = [EXUnit NSJSONSerializationWithmethod:@"kline.query" parameter:dataArray id:1020];
    
    
    if (self.webSocket.readyState == SR_OPEN) {
        [_webSocket send:data];    // 发送数据
        
    }
    NSArray * dataArray1  = @[_modle.name];
    NSData *data1 = [EXUnit NSJSONSerializationWithmethod:@"deals.subscribe" parameter:dataArray1 id:1763];
    if (self.webSocket.readyState == SR_OPEN) {
        [_webSocket send:data1];  
    }
    
}
// 断开连接
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
{
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string
{
    NSLog(@"Received \"%@\"", string);
}
// 关闭连接
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean;
{
    _webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload;
{
    NSLog(@"WebSocket received pong");
}
// 接收消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    [self stopLoadingAnimation];
    //收到服务端发送过来的消息
    if ([NSString isEmptyString:message]) {
        return;
    }
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
    NSString * id =@"";
    if (![NSString isEmptyString:message1[@"id"]])
    {
        id = message1[@"id"];
    }
    if (id.integerValue ==1020) {
        if ([message1[@"result"] isEqual:[NSNull null]]) {
            [EXUnit showSVProgressHUD:@"暂时没有数据"];
            return;
        }
        NSArray * array = message1[@"result"];
        if (array.count>0)
        {
            NSLog(@"---111111111");
            self.dataArray = [NSMutableArray arrayWithArray:array];
            
            _groupModel = [Y_KLineGroupModel objectWithArray:_dataArray model:_modle];
            self.groupModel = _groupModel;
            [self.modelsDict setObject:_groupModel forKey:self.type];
            [self.lineKView reloadData];
            
            
        }
        
    }
    if ([message1[@"method"] isEqualToString:@"deals.update"])
    {
        
        NSArray * data = message1[@"params"];
        
        if (data.count >0 &&  self.tradingArray.count ==0) {
            
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 处理耗时操作在此次添加
                self.tradingArray = [ChatModle mj_objectArrayWithKeyValuesArray:data[1]];
                if (self.tradingArray.count>20) //取最新20条
                {
                    self.tradingArray = [NSMutableArray arrayWithArray:[self.tradingArray subarrayWithRange:NSMakeRange(0, 20)]];
                }
                self.RecordVCt.dataArray = self.tradingArray;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.RecordVCt.tableView reloadData];
                    
                });
            });
            
            
            
        }else
        {
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{ // 处理耗时操作在此次添加
                NSArray *array = data[1];
                NSDictionary *dic = array[0];
                ChatModle * modle = [[ChatModle alloc] init];
                modle.price = dic[@"price"];
                modle.id = dic[@"id"];
                modle.time = dic[@"time"];
                modle.amount = dic[@"amount"];
                modle.type = dic[@"type"];
                [self.tradingArray insertObject:modle atIndex:0];
                if (self.tradingArray.count>20) //取最新20条
                {
                    self.tradingArray = [NSMutableArray arrayWithArray:[self.tradingArray subarrayWithRange:NSMakeRange(0, 20)]];
                }
                self.RecordVCt.dataArray = self.tradingArray;
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                   [self.RecordVCt.tableView reloadData];
                    
                });
            });
            
            
        }
        
    }
    
}

- (void)onClickFullScreenButtonWithTimeType:(Y_StockChartCenterViewType )timeType{
    if (!_isShowKLineFullScreenViewController) {
        [self showKLineFullScreenViewController];
    }
}

@end
